package com.yx.shop.service.admin.impl;

import com.yx.shop.common.Const;
import com.yx.shop.dao.admin.AdminUserDao;
import com.yx.shop.dao.admin.impl.AdminUserDaoImpl;
import com.yx.shop.entitly.User;
import com.yx.shop.entitly.pojo.ResponseResult;
import com.yx.shop.service.admin.AdminUserService;
import com.yx.shop.utils.JDBCUtils;
import com.yx.shop.utils.MD5Utils;
import com.yx.shop.utils.StrUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname AdminUserServiceImpl
 * @Description TODO:
 * @Date 2021/05/10 15:29
 * @Created by yx
 */
public class AdminUserServiceImpl implements AdminUserService {
    private AdminUserDao adminUserDao = new AdminUserDaoImpl();

    @Override
    public User login(String username, String password) {
        User user = null;
        try {
            JDBCUtils.begin();
            User temp = adminUserDao.login(username, password);
            //判断是否是管理员
            if (temp!=null&&temp.getUrole()== Const.UserInfo.IS_ADMIN){
                user=temp;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public ResponseResult<User> loginForAdmin(String username, String password) {
        //数据库中密码为加密
        User u = adminUserDao.login(username, MD5Utils.md5(password));
        //验证登录用户是否为管理员
        if (u != null) {
            if (u.getUrole()== Const.UserInfo.IS_ADMIN) {
                ResponseResult responseResult = new ResponseResult();
                return responseResult.createSuccess(3, "登录成功", u);
            }else{
                ResponseResult responseResult = new ResponseResult();
                return responseResult.createFail(2, "用户不是管理员无法登录", null);
            }
        } else {
            ResponseResult responseResult = new ResponseResult(1, "登录失败用户名或密码有误", null);
            return responseResult;
        }
    }

    @Override
    public List<User> searchByKey(String username, String gender) {
        //拼接实现多个条件查询
        String sql = "select * from user where 1=1";
        //利用集合长度可增减,达到多值条件
        List<String> args = new ArrayList<>();
        if (StrUtils.isNotEmpty(username)) {
            sql +=" and uname like ?";
            args.add("%"+username+"%");
        }
        if (StrUtils.isNotEmpty(gender)) {
            sql +=" and usex = ?";
            args.add(gender);
        }
        List<User> users = adminUserDao.searchByKey(sql, args.toArray());
        return users;
    }

    @Override
    public boolean deleteUserByUid(Integer uid) {
        boolean flag = false;
        try {
            JDBCUtils.begin();
            if (adminUserDao.deleteByUid(uid)>0) {
                flag=true;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return flag;
    }
}
